﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using BP.OA.Message;
using BP.DA;
using System.Data;
using System.Text;

namespace CCOA.App.Serv
{
    /// <summary>
    /// EmailServer 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    [System.Web.Script.Services.ScriptService]
    public class EmailServer : System.Web.Services.WebService
    {
        /// <summary>
        /// 获取我的收件箱
        /// </summary>
        /// <param name="FK_UserNo">用户编号</param>
        /// <returns></returns>
        [WebMethod]
        public string GetInBox(string FK_UserNo)
        {
            string getInBoxSql = String.Format("select A.OID as No,B.Title as Title,A.AddTime as RPT,A.Sender as Sender,"
                + "Received,B.AttachFile from  OA_MessageInBox A  inner join OA_Message B on A.FK_MsgNo=B.OID where FK_ReceiveUserNo='{0}'",
                BP.Web.WebUser.No);

            DataTable dt;
            if (!string.IsNullOrEmpty(FK_UserNo))
            {
                dt = DBAccess.RunSQLReturnTable(getInBoxSql);
                return DataTableConvertJson.DataTable2Json(dt, dt.Rows.Count);
            }
            else
            {
                return "用户编号不可为空!";
            }
        }

        /// <summary>
        /// 对收件/发件/草稿箱的操作
        /// </summary>
        /// <param name="OpeType">操作类型</param>
        /// <param name="FK_UserNo">用户编号</param>
        /// <param name="oid">选取的OID</param>
        /// <returns></returns>
        [WebMethod]
        public string DelDataByOpeType(string OpeType, string FK_UserNo, string oid)
        {
            string GetMesOidSql = null;
            string DelSendBox = null;
            string getNewSql = null;
            switch (OpeType)
            {
                case "DelInBoxByID"://收件箱 根据oid删除  
                    GetMesOidSql = string.Format("SELECT FK_MsgNo FROM  OA_MessageInBox where OID in ({0})", oid);
                    DelSendBox = string.Format("delete from OA_MessageInBox where FK_ReceiveUserNo='{0}'and OID in ({1})", FK_UserNo, oid);
                    getNewSql = "SELECT * FROM OA_Message where SendToUsers='{0}' and OID in ({1})";
                    return OpeMethod(GetMesOidSql, DelSendBox, FK_UserNo, 2, getNewSql);
                case "DelAllInBox"://收件箱 全部删除  
                    GetMesOidSql = string.Format("SELECT FK_MsgNo FROM  OA_MessageInBox where FK_ReceiveUserNo = '{0}'", FK_UserNo);
                    DelSendBox = string.Format("delete from OA_MessageInBox where FK_ReceiveUserNo='{0}'", FK_UserNo);
                    getNewSql = "SELECT * FROM OA_Message where SendToUsers='{0}' and OID in ({1})";
                    return OpeMethod(GetMesOidSql, DelSendBox, FK_UserNo, 2, getNewSql);
                case "DelSendBoxByID"://发件箱 根据oid删除  
                    GetMesOidSql = string.Format("SELECT FK_MsgNo FROM  OA_MessageSendBox where OID in ({0})", oid);
                    DelSendBox = string.Format("delete from OA_MessageSendBox where FK_SendUserNo='{0}' and OID in ({1})", FK_UserNo, oid);
                    getNewSql = "SELECT * FROM OA_Message where FK_UserNo='{0}' and OID in ({1})";
                    return OpeMethod(GetMesOidSql, DelSendBox, FK_UserNo, 1, getNewSql);
                case "DelAllSendBox"://发件箱 全部删除
                    GetMesOidSql = string.Format("SELECT FK_MsgNo FROM  OA_MessageSendBox where FK_SendUserNo = '{0}'", FK_UserNo);
                    DelSendBox = string.Format("delete from OA_MessageSendBox where FK_SendUserNo='{0}'", FK_UserNo);
                    getNewSql ="SELECT * FROM OA_Message where FK_UserNo='{0}' and OID in ({1})";
                    return OpeMethod(GetMesOidSql, DelSendBox, FK_UserNo, 1, getNewSql);
                case "DelDraftBoxByID"://草稿箱 根据oid删除  
                    GetMesOidSql = string.Format("SELECT FK_MsgNo FROM  OA_MessageDraftBox where OID in ({0})", oid);
                    DelSendBox = string.Format("delete from OA_MessageDraftBox where FK_UserNo='{0}' and OID in ({1})", FK_UserNo, oid);
                    getNewSql = "SELECT * FROM OA_Message where FK_UserNo='{0}' and OID in ({1})";
                    return OpeMethod(GetMesOidSql, DelSendBox, FK_UserNo, 0, getNewSql);
                case "DelAllDraftBox"://草稿箱 全部删除
                    GetMesOidSql = string.Format("SELECT FK_MsgNo FROM  OA_MessageDraftBox where FK_UserNo = '{0}'", FK_UserNo);
                    DelSendBox = string.Format("delete from OA_MessageDraftBox where FK_UserNo='{0}'", FK_UserNo);
                    getNewSql = "SELECT * FROM OA_Message where FK_UserNo='{0}' and OID in ({1})";
                    return OpeMethod(GetMesOidSql, DelSendBox, FK_UserNo, 0, getNewSql);
                default:
                    return "false";
            }
        }
        /// <summary>
        /// 根据DelDataByOpeType方法传入职执行操作
        /// </summary>
        /// <param name="getMesOidSql">获取操作表字段FK_MsgNo的SQL</param>
        /// <param name="delSendBox">根据参数删除对应表数据的SQL</param>
        /// <param name="FK_UserNo">用户编号</param>
        /// <param name="FromType">删除来源类型</param>
        /// <param name="NewSql">获取OA_Message源数据执行insert到回收站</param>
        /// <returns></returns>
        public string OpeMethod(string getMesOidSql, string delSendBox, string FK_UserNo, int FromType, string NewSql)
        {
            string GetMesOidSql = getMesOidSql;
            string DelSendBox = delSendBox;
            DataTable GetMesOidDt = DBAccess.RunSQLReturnTable(GetMesOidSql);
            string GetMesOid = null;
            for (int i = 0; i < GetMesOidDt.Rows.Count; i++)
            {
                string split = ",";
                if (i == GetMesOidDt.Rows.Count - 1)
                {
                    split = "";
                }
                GetMesOid += (GetMesOidDt.Rows[i]["FK_MsgNo"].ToString() + split);
            }
            DelSendBox = delSendBox;
            DBAccess.RunSQL(DelSendBox);
            //insert到垃圾箱中
            string getNewSql = string.Format(NewSql, FK_UserNo, GetMesOid);
            DataTable dt = DBAccess.RunSQLReturnTable(getNewSql);
            RecycleBox rb = null;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                rb = new RecycleBox();
                rb.FK_MsgNo = int.Parse(dt.Rows[i]["OID"].ToString());
                rb.FK_UserNo = dt.Rows[i]["FK_UserNo"].ToString();
                rb.AddTime = DateTime.Parse(dt.Rows[i]["AddTime"].ToString());
                rb.ReceivedTime = DateTime.Now.ToString();
                rb.Received = false;
                rb.FromType = FromType;
                rb.Insert();
            }
            return "操作成功!";
        }

        /// <summary>
        /// 写邮件(成功发送或保存草稿)
        /// </summary>
        /// <param name="Title">标题</param>
        /// <param name="Doc">内容</param>
        /// <param name="MessageState">0草稿或1发送</param>
        /// <param name="AttachFile">附件</param>
        /// <param name="AddTime">添加时间</param>
        /// <param name="FromPer">发送人</param>
        /// <param name="ToPer">接收人</param>
        /// <param name="CopyPer">抄写人</param>
        /// <returns></returns>
        [WebMethod]
        public string SendEamil(string Title, string Doc, int MessageState, string AttachFile,
                       string FromPer, string ToPer, string CopyPer)                               
        {
            DateTime AddTime = DateTime.Now;

            string fromToPer = "'" + FromPer + "'" + "," + "'" + ToPer + "'";
            if (!string.IsNullOrEmpty(FromPer) && !string.IsNullOrEmpty(ToPer))
            {
                string beSureSql = string.Format("SELECT * FROM Port_Emp where No in ({0})", fromToPer);
                int getCount = DBAccess.RunSQLReturnCOUNT(beSureSql);
                #region
                if (getCount != 2)
                {
                    return "各部门均无此人!";
                }
                else
                {
                    if (MessageState == 1 || MessageState == 0)
                    {
                        #region //写邮件 发送成功时或保存时执行代码
                        if (MessageState == 1)//成功发送
                        {
                            #region insert   表OA_Message
                            BP.OA.Message.Message ma = new BP.OA.Message.Message();
                            ma.AddTime = AddTime;
                            ma.Title = Title;
                            ma.AttachFile = AttachFile;
                            ma.Doc = Doc;
                            ma.FK_UserNo = FromPer;
                            ma.MessageState = MessageState;
                            ma.SendToUsers = ToPer;
                            ma.CopyToUsers = CopyPer;
                            ma.Insert();
                            #endregion
                            #region  利用FromPer作为唯一查询，获取OID   insert   表OA_MessageSendBox与OA_MessageInBox都需要
                            string getNewSql = string.Format("SELECT OID FROM  OA_Message where FK_UserNo='{0}' and AddTime='{1}'", FromPer, AddTime);
                            DataTable dt = DBAccess.RunSQLReturnTable(getNewSql);
                            SendBox sb = null;
                            if (!string.IsNullOrEmpty(dt.Rows[0]["OID"].ToString()))
                            {
                                sb = new SendBox();
                                sb.Receiver = ToPer;
                                sb.FK_SendUserNo = FromPer;
                                sb.FK_MsgNo = int.Parse(dt.Rows[0]["OID"].ToString());
                                sb.SendTime = AddTime;
                                sb.Insert();
                            }
                            #endregion
                            #region insert表OA_MessageInBox
                            InBox ib = new InBox();
                            ib.FK_MsgNo = int.Parse(dt.Rows[0]["OID"].ToString());
                            ib.FK_ReceiveUserNo = ToPer;
                            ib.Sender = FromPer;
                            ib.Doc = Doc;
                            ib.AddTime = AddTime;
                            ib.ReceiveTime = DateTime.Now.ToString();
                            ib.Received = false;
                            ib.IsCopy = true;
                            ib.Title = Title;
                            ib.AttachFile = AttachFile;
                            ib.Insert();
                            #endregion
                            return "true";
                        }
                        else //保存草稿
                        {
                            #region insert表OA_Message
                            BP.OA.Message.Message ma = new BP.OA.Message.Message();
                            ma.AddTime = AddTime;
                            ma.Title = Title;
                            ma.AttachFile = AttachFile;
                            ma.Doc = Doc;
                            ma.FK_UserNo = FromPer;
                            ma.MessageState = MessageState;
                            ma.SendToUsers = ToPer;
                            ma.CopyToUsers = CopyPer;
                            int i = ma.Insert();
                            #endregion
                            #region insert表OA_MessageDraftBox
                            string getNewSql = string.Format("SELECT OID FROM  OA_Message where FK_UserNo='{0}' and AddTime='{1}'", FromPer, AddTime);
                            DataTable dt = DBAccess.RunSQLReturnTable(getNewSql);
                            if (!string.IsNullOrEmpty(dt.Rows[0]["OID"].ToString()))
                            {
                                DraftBox df = new DraftBox();
                                df.FK_MsgNo = int.Parse(dt.Rows[0]["OID"].ToString());
                                df.AddTime = AddTime;
                                df.FK_UserNo = FromPer;
                                df.Insert();
                            }
                            #endregion
                            return "true";
                        }
                        #endregion
                    }
                    else
                    {
                        return "false";
                    }
                }
                #endregion
            }
            else
            {
                return "收/发用户编号不可为空!";
            }
        }

        /// <summary>
        /// 发件箱webservice
        /// </summary>
        /// <param name="FK_UserNo">用户编号</param>
        /// <returns></returns>
        [WebMethod]
        public string GetSendBox(string FK_UserNo)
        {
            string getSendBoxSql = String.Format("select A.OID as No,B.Title as Title,A.SendTime as RPT,Receiver as Geter,B.AttachFile from OA_MessageSendBox A inner join OA_Message B on A.FK_MsgNo=B.OID where FK_SendUserNo='{0}'", FK_UserNo);

            DataTable dt;
            if (!string.IsNullOrEmpty(FK_UserNo))
            {
                dt = DBAccess.RunSQLReturnTable(getSendBoxSql);
                return DataTableConvertJson.DataTable2Json(dt, dt.Rows.Count);
            }
            else
            {
                return "用户编号不可为空!";
            }
        }

        /// <summary>
        /// 草稿箱webservice
        /// </summary>
        /// <param name="FK_UserNo">用户编号</param>
        /// <returns></returns>
        [WebMethod]
        public string GetDraftBox(string FK_UserNo)
        {
            string getDraftBoxSql = String.Format("select A.OID as No,B.Title as Title,A.AddTime as RPT,B.SendToUsers as Geter,B.AttachFile from OA_MessageDraftBox A inner join OA_Message B on A.FK_MsgNo=B.OID where B.FK_UserNo='{0}'", FK_UserNo);

            DataTable dt;
            if (!string.IsNullOrEmpty(FK_UserNo))
            {
                dt = DBAccess.RunSQLReturnTable(getDraftBoxSql);
                return DataTableConvertJson.DataTable2Json(dt, dt.Rows.Count);
            }
            else
            {
                return "用户编号不可为空!";
            }
        }

        /// <summary>
        /// 垃圾箱webservice
        /// </summary>
        /// <param name="FK_UserNo">用户编号</param>
        /// <returns></returns>
        [WebMethod]
        public string GetRecycleBox(string FK_UserNo)
        {
            string getRecycleBoxSql = String.Format("select A.OID as No,B.Title as Title,A.AddTime as RPT,A.FromType as FromType,A.FK_UserNo,B.AttachFile from OA_MessageRecycleBox A inner join OA_Message B on A.FK_MsgNo=B.OID where A.FK_UserNo='{0}'", FK_UserNo);

            DataTable dt;
            if (!string.IsNullOrEmpty(FK_UserNo))
            {
                dt = DBAccess.RunSQLReturnTable(getRecycleBoxSql);
                return DataTableConvertJson.DataTable2Json(dt, dt.Rows.Count);
            }
            else
            {
                return "用户编号不可为空!";
            }
        }

        /// <summary>
        /// 删除垃圾箱数据some/all?
        /// </summary>
        /// <param name="IsDelAll">是"1"/否"0"清空</param>
        /// <param name="FK_UserNo">用户编号</param>
        /// <param name="oid">选中项oid</param>
        /// <returns></returns>
        [WebMethod]
        public string DelRecycleBox(int IsDelAll, string FK_UserNo, string oid)
        {
            string DelSendBox = null;
            if (IsDelAll == 1 || IsDelAll == 0)
            {
                if (IsDelAll == 1)
                {
                    string GetMesOidSql = string.Format("SELECT FK_MsgNo FROM  OA_MessageRecycleBox where FK_UserNo = '{0}'", FK_UserNo);
                    DataTable GetMesOidDt = DBAccess.RunSQLReturnTable(GetMesOidSql);
                    string GetMesOid = null;
                    for (int i = 0; i < GetMesOidDt.Rows.Count; i++)
                    {
                        string split = ",";
                        if (i == GetMesOidDt.Rows.Count - 1)
                        {
                            split = "";
                        }
                        GetMesOid += (GetMesOidDt.Rows[i]["FK_MsgNo"].ToString() + split);
                    }
                    DelSendBox = string.Format("delete from OA_MessageSendBox where OA_MessageRecycleBox='{0}'", FK_UserNo);
                    string DelMessage = string.Format("delete from OA_Message where FK_UserNo = '{0}' and OID in({1})", FK_UserNo, GetMesOid);
                    DBAccess.RunSQL(DelSendBox);
                    DBAccess.RunSQL(DelMessage);
                    return "全部删除成功!";
                }
                else
                {
                    string GetMesOidSql = string.Format("SELECT FK_MsgNo FROM  OA_MessageRecycleBox where OID in ({0})", oid);
                    DataTable GetMesOidDt = DBAccess.RunSQLReturnTable(GetMesOidSql);
                    string GetMesOid = null;
                    for (int i = 0; i < GetMesOidDt.Rows.Count; i++)
                    {
                        string split = ",";
                        if (i == GetMesOidDt.Rows.Count - 1)
                        {
                            split = "";
                        }
                        GetMesOid += (GetMesOidDt.Rows[i]["FK_MsgNo"].ToString() + split);
                    }
                    DelSendBox = string.Format("delete from OA_MessageRecycleBox where FK_UserNo='{0}' and OID in ({1})", FK_UserNo, oid);
                    string DelMessage = string.Format("delete from OA_Message where FK_UserNo='{0}' and  OID in ({1})", FK_UserNo, GetMesOid);
                    DBAccess.RunSQL(DelSendBox);
                    DBAccess.RunSQL(DelMessage);
                    return "选中项删除成功";
                }
            }
            else
            {
                return "false";
            }
        }
        /// <summary>
        /// 恢复数据
        /// </summary>
        /// <param name="FK_UserNo">用户编号</param>
        /// <param name="oid">选中项oid</param>
        /// <returns></returns>
        [WebMethod]
        public string BackDataRecycleBox(string FK_UserNo, string oid)
        {
            string GetMesOid = null;
            string BackDataSql = string.Format("select FK_MsgNo, FromType from OA_MessageRecycleBox where OID in ({0}) and FK_UserNo='{1}'", oid, FK_UserNo);
            DataTable dt = DBAccess.RunSQLReturnTable(BackDataSql);
            //获取FK_MsgNo
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string split = ",";
                if (i == dt.Rows.Count - 1)
                {
                    split = "";
                }
                GetMesOid += (dt.Rows[i]["FK_MsgNo"].ToString() + split);
            }

            string GetMesSql = string.Format("SELECT *  FROM OA_Message WHERE OID in({0})", GetMesOid);
            DataTable GetData = DBAccess.RunSQLReturnTable(GetMesSql);
            //0草稿1发件2收件
            BP.OA.Message.SendBox sb = null;
            DraftBox df = null;
            BP.OA.Message.InBox ib = null;
            if (GetData.Rows.Count != 0)
            {
                #region
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["FromType"].ToString()) == 0)
                    {
                        df = new DraftBox();
                        df.FK_MsgNo = int.Parse(GetData.Rows[i]["OID"].ToString());
                        df.AddTime = DateTime.Parse(GetData.Rows[i]["AddTime"].ToString());
                        df.FK_UserNo = GetData.Rows[i]["SendToUsers"].ToString();
                        df.Insert();
                    }
                    else
                    {
                        if (int.Parse(dt.Rows[i]["FromType"].ToString()) == 1)
                        {
                            sb = new BP.OA.Message.SendBox();
                            sb.Receiver = GetData.Rows[i]["SendToUsers"].ToString();
                            sb.FK_SendUserNo = GetData.Rows[i]["FK_UserNo"].ToString();
                            sb.FK_MsgNo = int.Parse(GetData.Rows[i]["OID"].ToString());
                            sb.SendTime = DateTime.Parse(GetData.Rows[i]["AddTime"].ToString());
                            sb.Insert();
                        }
                        else
                        {
                            ib = new BP.OA.Message.InBox();
                            ib.FK_MsgNo = int.Parse(GetData.Rows[i]["OID"].ToString());
                            ib.FK_ReceiveUserNo = GetData.Rows[i]["SendToUsers"].ToString();
                            ib.Sender = GetData.Rows[i]["FK_UserNo"].ToString();
                            ib.Doc = GetData.Rows[i]["Doc"].ToString();
                            ib.AddTime = DateTime.Parse(GetData.Rows[i]["AddTime"].ToString());
                            ib.ReceiveTime = DateTime.Now.ToString();
                            ib.Received = false;
                            ib.IsCopy = true;
                            ib.Title = GetData.Rows[i]["Title"].ToString();
                            ib.AttachFile = GetData.Rows[i]["AttachFile"].ToString();
                            ib.Insert();
                        }
                    }
                }
                #endregion
            }


            string DelSome = String.Format("Delete FROM OA_MessageRecycleBox Where FK_UserNo='{0}' and OID in ({1});", FK_UserNo, oid);
            DBAccess.RunSQL(DelSome);
            return "操作成功!";
        }

        //[WebMethod]
        //public string HelloWorld()
        //{
        //    return "Hello World";
        //}
    }
}
